package com.quexin.pickmedialib;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;


import com.qmuiteam.qmui.util.QMUIDisplayHelper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;


public class ImageUtils {


    public static String saveBitmapPNG(Context context, Bitmap bitmap, String path) {
        return saveBitmap(context, bitmap, Bitmap.CompressFormat.PNG,
                path, getPngName(), 100);
    }

    public static String getPngName() {
        return "IMG_" + FileUtils.getRandomFileName() + ".png";
    }


    public static String saveBitmapJPG(Context context, Bitmap bitmap, String path) {
        return saveBitmap(context, bitmap, Bitmap.CompressFormat.JPEG,
                path, getJpgName(), 100);
    }

    public static String getJpgName() {
        return "IMG_" + FileUtils.getRandomFileName() + ".jpg";
    }

    /**
     * 保存Bitmap为图片，返回图片路径
     */
    public static String saveBitmap(Context context, Bitmap bitmap, Bitmap.CompressFormat format,
                                    String parentPath, String fileName, int quality) {
        File file = new File(parentPath, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(format, quality, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = file.getAbsolutePath();
        MediaUtils.refreshSystemMedia(context, path);
        System.out.println("saveBitmap(context, bitmap, format, fileName, quality): " + path);
        return path;
    }

    /**
     * 获取手机图片大小
     * size[0] 宽
     * size[1] 高
     */
    public static int[] getImageSize(String imagePath) {
        int[] size = {200, 200};
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        size[0] = options.outWidth;
        size[1] = options.outHeight;
        int orientation = ExifInterface.ORIENTATION_NORMAL;
        try {
            ExifInterface exifInterface = new ExifInterface(imagePath);
            orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
        } catch (IOException e) {
            e.printStackTrace();
        }
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
            case ExifInterface.ORIENTATION_ROTATE_270:
                size[0] = options.outHeight;
                size[1] = options.outWidth;
                break;
        }
        return size;
    }

    /**
     * 绘制已经测量过的View
     */
    public static Bitmap getViewBitmap(View view) {
        int width = view.getWidth();
        int height = view.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }


    /**
     * 合成图片
     *
     * @param background 背景图
     * @param foreground 前景图
     * @return Bitmap
     */
    public static Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
        if (background == null) {
            return null;
        }
        if (foreground == null) {
            return background;
        }
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        // 使前景图缩放和背景图一样大
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(bgWidth / (float) fgWidth, bgHeight / (float) fgHeight);
        foreground = Bitmap.createBitmap(foreground, 0, 0, foreground.getWidth(),
                foreground.getHeight(), matrix, true);
        // 合成
        Bitmap newMap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newMap);
        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, 0, 0, null);
        canvas.save();
        canvas.restore();
        return newMap;
    }

    /**
     * 合成图片
     *
     * @param background 背景图
     * @param foreground 前景图
     * @param width      前景图宽
     * @param height     前景图高
     * @param x          前景图位置x
     * @param y          前景图位置y
     * @return Bitmap
     */
    public static Bitmap combineBitmap(
            Bitmap background, Bitmap foreground, int width, int height, float x, float y) {
        if (background == null) {
            return null;
        }
        if (foreground == null) {
            return background;
        }
        // 使前景图缩放指定大小
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(width / (float) fgWidth, height / (float) fgHeight);
        foreground = Bitmap.createBitmap(foreground, 0, 0, foreground.getWidth(),
                foreground.getHeight(), matrix, true);
        // 合成
        Bitmap newMap = Bitmap.createBitmap(background.getWidth(),
                background.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newMap);
        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, x, y, null);
        canvas.save();
        canvas.restore();
        return newMap;
    }

    /**
     * 压缩
     */
    public static String compress(
            String path, float ratio, Bitmap.CompressFormat format, int quality, String savePath) {
        // 大小缩放
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        Matrix matrix = new Matrix();
        matrix.postRotate(readPictureDegree(path));
        matrix.postScale(ratio, ratio);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        // 质量
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(format, quality, baos);
        try {
            FileOutputStream fos = new FileOutputStream(new File(savePath));
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return savePath;
    }

    /**
     * 获取图片旋转角度
     */
    public static int readPictureDegree(String srcPath) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(srcPath);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 获取视频第一帧图片
     */
    public static Bitmap getImageFromVideo(String videoPath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(videoPath, new HashMap<>());
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }

    /**
     * Bitmap 转 byte[]
     */
    public static byte[] toByte(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * Bitmap 转 Base64编码的字符串
     */
    public static String toBase64(Bitmap bitmap) {
        byte[] bytes = toByte(bitmap);
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    /**
     * 将手机图片 转 Base64编码的字符串
     */
    public static String toBase64(String path, boolean needData) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            int i = is.read(data);
            System.out.println("toBase64(path, needData)_read: " + i);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.NO_CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (needData) {
            return "data:image/png;base64," + result;
        } else {
            return result;
        }
    }

    /**
     * Base64编码的字符串 转 Bitmap
     */
    public static Bitmap toBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * Drawable 转 Bitmap
     */
    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}
